package com.tencent.wxcloudrun.service;

import com.tencent.wxcloudrun.model.User;
import com.tencent.wxcloudrun.repository.UserRepository;
import com.tencent.wxcloudrun.utils.PasswordUtil;
import org.springframework.stereotype.Service;
import java.util.Optional;

@Service
public class AuthService {

    final UserRepository userRepository;

    public AuthService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // 注册逻辑
    public void register(String mobile, String password) {
        if (userRepository.existsByMobile(mobile)) {
            throw new RuntimeException("手机号已注册");
        }
        if (password.length() < 8) {
            throw new RuntimeException("密码不能小于8位");
        }
        // 生成加密密码
        String salt = PasswordUtil.generateSalt();
        String hashedPassword = PasswordUtil.hashPassword(password, salt);

        User user = new User();
        user.setMobile(mobile);
        user.setPassword(hashedPassword);
        user.setSalt(salt);
        userRepository.save(user);
    }

    // 重置密码
    public void resetPassword(String mobile, String newPwd) {
        Optional<User> userOpt = userRepository.findByMobile(mobile);
        if (!userOpt.isPresent()) {
            throw new RuntimeException("手机号未注册");
        }
        User user = userOpt.get();
        String salt = PasswordUtil.generateSalt();
        String hashedPassword = PasswordUtil.hashPassword(newPwd, salt);
        user.setSalt(salt);
        user.setPassword(hashedPassword);
        userRepository.save(user);
    }

    // 修改密码
    public void updatePassword(String mobile, String oldPassword, String newPassword) {
        Optional<User> userOpt = userRepository.findByMobile(mobile);
        if (!userOpt.isPresent()) {
            throw new RuntimeException("手机号未注册");
        }

        User user = userOpt.get();
        if (!oldPassword.equals("888888")) {
            throw new RuntimeException("密码未重置，请联系管理员");
        }

        String salt = PasswordUtil.generateSalt();
        user.setSalt(salt);
        user.setPassword(PasswordUtil.hashPassword(newPassword, salt));
        userRepository.save(user);
    }
}